package com.raizlabs.android.dbflow.config;

import java.lang.reflect.Field;
import java.util.Map;
import java.util.Set;

/**
 * {@link  FlowManager} 的扩展, 添加了断开数据库的功能
 */

public class FlowManagerExt {

    /**
     * 断开当前连接的数据库
     */
    public static synchronized void disConnect() {
        try {
            Class c = FlowManager.class;
            Field globalDatabaseHolderField = c.getDeclaredField("globalDatabaseHolder");
            globalDatabaseHolderField.setAccessible(true);
            DatabaseHolder holder = (DatabaseHolder) globalDatabaseHolderField.get(c);
            Set<Map.Entry<Class<?>, DatabaseDefinition>> entrySet = holder.databaseClassLookupMap.entrySet();
            for (Map.Entry<Class<?>, DatabaseDefinition> value : entrySet) {
                DatabaseDefinition definition = value.getValue();
                definition.getTransactionManager().stopQueue();
                definition.getHelper().closeDB();
                Field openHelperField = DatabaseDefinition.class.getDeclaredField("openHelper");
                openHelperField.setAccessible(true);
                openHelperField.set(definition, null);
            }
            FlowManager.config = null;
            holder.reset();
            Field loadedModulesField = c.getDeclaredField("loadedModules");
            loadedModulesField.setAccessible(true);
            Set set = (Set) loadedModulesField.get(c);
            set.clear();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
